﻿package cc.telecomdigital.tdstock.trading;
	
import java.util.ArrayList;
import java.util.List;

import com.lightstreamer.ls_client.UpdateInfo;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.Application_Framework.LS_ItemRequestType;
import cc.telecomdigital.tdstock.Framework.UniqueItem.DeviceInfo;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.LS_SubscriptionItem;
import cc.telecomdigital.tdstock.Services.LS_UserClient.CONNECTION_STATUS;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Response;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;

import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockHoldItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockPortfolioRecord;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetPortfolio;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeGetPortfolio.ITradeGetPortfolioResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetPortfolio.TradeGetPortfolioResult;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Tools.Trade_StockFunctionTools;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;
import cc.telecomdigital.tdstock.trading.widget.SwipeView;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

public class Trade_AcctHold_SubActivity extends Trade_TemplateActivity
	implements View.OnClickListener, AdapterView.OnItemClickListener, ILS_UserClient_Response
{
	private int		prevWidth;
	private String      systemLang;
	
	private SwipeView  swipFlipper;
	
	@Override
	protected void onCreate(Bundle iSaveInstance)
	{
		super.onCreate(iSaveInstance);
		setContentView(R.layout.account_stockhold);
		systemLang = DeviceInfo.GetLanguageString();
		
		// Map the button function
		// Set Header as UserName
		TextView textViewObj = (TextView) findViewById(R.id.view_acctheader_Title);
		if (TradeAppInfo.IsDemoAccount())
			textViewObj.setText(TradeAppInfo.GetUserName());
		else
			textViewObj.setText(R.string.holdingBalText);

		ImageButton imgButton;

		imgButton = (ImageButton) findViewById(R.id.view_acctheader_Refresh);
		imgButton.setVisibility(View.VISIBLE);
		imgButton.setOnClickListener(this);

		imgButton = (ImageButton) findViewById(R.id.view_acctheader_Home);
		imgButton.setOnClickListener(this);

		stockHoldList = new ArrayList<Trade_StockHoldItem>();

		stockHoldListAdpater = new StockHoldItemAdapter(this,
				android.R.layout.simple_list_item_1,
				R.layout.view_stockhold_itemlist, fScrWidthPixel,
				stockHoldList);

		stockHoldListView = (ListView) findViewById(R.id.stockhold_listItem);
		stockHoldListView.setDividerHeight(0);
		stockHoldListView.setAdapter(stockHoldListAdpater);
		stockHoldListView.setOnItemClickListener(this);

		swipFlipper = (SwipeView)findViewById(R.id.view_stockhold_total_swipeView);
		
		prevWidth = 0;
	}

	// Happens when first with to this View
	@Override
	protected void onResume()
	{
		super.onResume();
		systemLang = DeviceInfo.GetLanguageString();
		LayoutAdjustment(fScrWidthPixel);
		
		if (TradeAppInfo.IsStockPortfolioRecordEmpty() == false)
		{
			InformationRefresh();
			SubscribeAccountHold();
		}			
		else
			StockHoldDataRequest();
	}	
	
	/** Update Layout adjustment **/
	private void LayoutAdjustment(int iScrWidth)
	{
		if (prevWidth != iScrWidth)
		{
			prevWidth = iScrWidth;

			TextView textViewObj;

			stockHoldListAdpater.SetScreenWidth(iScrWidth);

			textViewObj = (TextView) findViewById(R.id.view_account_stockhold_h1);
			textViewObj.setWidth(stockHoldListAdpater.itemOneWidth);
			textViewObj = (TextView) findViewById(R.id.view_account_stockhold_h2);
			textViewObj.setWidth(stockHoldListAdpater.itemTwoWidth);
			textViewObj = (TextView) findViewById(R.id.view_account_stockhold_h3);
			textViewObj.setWidth(stockHoldListAdpater.itemThreeWidth);
			textViewObj = (TextView) findViewById(R.id.view_account_stockhold_h4);
			textViewObj.setWidth(stockHoldListAdpater.itemFourthWidth);
			textViewObj = (TextView) findViewById(R.id.view_account_stockhold_h5);
			textViewObj.setWidth(stockHoldListAdpater.itemFifthWidth);

			stockHoldListAdpater.notifyDataSetInvalidated();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration iNewChange)
	{
		super.onConfigurationChanged(iNewChange);
		LayoutAdjustment(fScrWidthPixel);
		if (stockHoldListView != null)
		{
			stockHoldListView.setSelectionAfterHeaderView();
			stockHoldListView.setSelectionFromTop(0, 0);
		}
	}

	/** Text Adapter to display the current stock on portfolio **/
	private class StockHoldItemAdapter extends
			ArrayAdapter<Trade_StockHoldItem>
	{
		// Reference to the Item List
		private int	itemLayout;
		public int	itemOneWidth, itemTwoWidth, itemThreeWidth,
					itemFourthWidth, itemFifthWidth;

		final int		ratio1	= 60;
		final int		ratio2	= 94;
		final int		ratio3	= 90;

		private int	redColor;
		private int	link_greenColor;
		private int    dimYellowColor;

		public StockHoldItemAdapter(Context iContext, int iListLayout,
				int iItemLayout, int iScrWidth,
				List<Trade_StockHoldItem> iItemList)
		{
			super(iContext, iItemLayout, iItemList);
			itemLayout = iItemLayout;
			SetScreenWidth(iScrWidth);

			Resources contRes;

			contRes = getResources();
			redColor = contRes.getColor(R.color.Red);
			link_greenColor = contRes.getColor(R.color.link_Green);
			dimYellowColor = contRes.getColor(R.color.DimYellow);
		}

		public void SetScreenWidth(int iScrWidth)
		{
			float factor = (float) iScrWidth
					/ Trade_AppConstant.designschemeWidth;

			itemOneWidth = (int) (ratio1 * factor);
			itemTwoWidth = (int) (ratio2 * factor);
			itemThreeWidth = (int) (ratio3 * factor);
			itemFourthWidth = (int) ((Trade_AppConstant.designschemeWidth
					- ratio1 - ratio2 - ratio3) * factor);
			itemFifthWidth = (int) (iScrWidth - itemThreeWidth - itemFourthWidth);
		}

		private int[]	_listLayout	= new int[] {
										R.drawable.at_acctcombo_lslct_even,
										R.drawable.at_acctcombo_lslct_odd };

		@Override
		public View getView(int iPosition, View iContextView,
				ViewGroup iParent)
		{
			int      colorValue;
			TextView textViewObj;
			String   curSign;

			View viewObj;

			viewObj = iContextView;
			if (viewObj == null)
			{
				LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				viewObj = inflatObj.inflate(itemLayout, null);
			}

			Trade_StockHoldItem item;
			String convertString;

			item = getItem(iPosition);
			viewObj.setBackgroundDrawable(getResources().getDrawable(
					_listLayout[iPosition % 2]));

			if (item != null)
			{
				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockhold_itemlist_StockCode);
				textViewObj.setWidth(itemOneWidth);
				textViewObj.setText(item.stockCode);

				textViewObj = (TextView) viewObj
						.findViewById(R.id.view_stockhold_itemlist_StockName);
				textViewObj.setWidth(itemTwoWidth);
				if (systemLang.equals("lang_cht"))
					textViewObj.setText(item.chnName);
				else
					textViewObj.setText(item.engName);

				//Quantity for notification of short or have */
				textViewObj = (TextView) viewObj .findViewById(R.id.view_stockhold_itemlist_Quantity);
				textViewObj.setWidth(itemThreeWidth);
				convertString = Trade_StockFunctionTools.ConvertFormatUnitFromString(item.onHandVolume,
												Trade_AppConstant.maxStockQuantityDisplayEntry);
				textViewObj.setText(convertString);
				
				if (item.IsShortSale())
					textViewObj.setTextColor(redColor);
				else
					textViewObj.setTextColor(link_greenColor);
				
				//Last Close price				
				textViewObj = (TextView) viewObj.findViewById(R.id.view_stockhold_itemlist_LastPrice);
				textViewObj.setWidth(itemFourthWidth);				
				
				convertString = Trade_StockFunctionTools.AutoFillInDecimal(item.lastClosedPrice,
																Trade_AppConstant.priceValueStringWithDec);
				if (item.currencyType.equals(TradeAppInfo.CNYCode))
				{
					curSign = TradeAppInfo.CNYSign;
					colorValue = dimYellowColor;
				}					
				else if (item.currencyType.equals(TradeAppInfo.USDCode))
				{
					curSign = TradeAppInfo.USDSign;
					colorValue = dimYellowColor;
				}					
				else
				{
					curSign = TradeAppInfo.HKDSign;
					colorValue = link_greenColor;
				}
				
				convertString = curSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);				
				textViewObj.setText(convertString);
				textViewObj.setTextColor(colorValue);
				
				//AmountWorth
				textViewObj = (TextView) viewObj.findViewById(R.id.view_stockhold_itemlist_TotalWorth);
				textViewObj.setTextColor(colorValue);

				convertString = Trade_StockFunctionTools.AutoFormatPriceToCents(item.totalWorth);
				convertString = curSign + Trade_StockFunctionTools.AddFormatToThousand(convertString);
				textViewObj.setWidth(itemFifthWidth);
				textViewObj.setText(convertString);
			}

			return viewObj;
		}
	}
	
	@Override
	protected void onPause()
	{
		if (toastDisplay != null)
			toastDisplay.cancel();
		
		LightStreamerTimeoutTaskCancel();
		DetachedDisconnectMessage();			

		super.onPause();
	}
	
	private View CreateStockBalanceInfo( String iDollarCode, String iDollarContent, boolean iLeft, boolean iRight)
	{
		View     viewObj;
		String   formatText, dollarSign;
		TextView textViewObj;
		
		LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		viewObj = inflatObj.inflate(R.layout.view_account_stockhold_total, null);
		
		textViewObj = (TextView)viewObj.findViewById(R.id.view_account_stockhold_total_CurrencyText);
		textViewObj.setText(iDollarCode);

		if (iDollarCode.equals(TradeAppInfo.CNYCode))
			dollarSign = TradeAppInfo.CNYSign;
		else if (iDollarCode.equals(TradeAppInfo.USDCode))
			dollarSign = TradeAppInfo.USDSign;
		else
			dollarSign = TradeAppInfo.HKDSign;
		
		formatText = Trade_StockFunctionTools.AutoFormatPriceToCents(iDollarContent);
		textViewObj = (TextView)viewObj.findViewById(R.id.view_account_stockhold_total_AmountWorth);		
		textViewObj.setText(dollarSign + Trade_StockFunctionTools .AddFormatToThousand(formatText));
		
		if (iDollarCode.equals(TradeAppInfo.HKDCode) == false)
			textViewObj.setTextColor(getResources().getColor(R.color.DimYellow));
		
		
		if (!iLeft)			
			viewObj.findViewById(R.id.view_account_stockhold_total_LeftArrow).setVisibility(View.GONE);
			
		if (!iRight)			
			viewObj.findViewById(R.id.view_account_stockhold_total_RightArrow).setVisibility(View.GONE);		
		
		return viewObj;
	}
	
	
	private List<Trade_StockHoldItem>	stockHoldList;
	private ListView				stockHoldListView;
	// Create the array adapter to bind the array to the list view
	private StockHoldItemAdapter		stockHoldListAdpater;
	//Toast need to be static in order to make the cancel to work
	private static Toast               toastDisplay = null;
	
	/** Request information on Profile from server **/
	private void InformationRefresh()
	{
		int count;
		Trade_StockPortfolioRecord content;

		stockHoldList.clear();
		content = TradeAppInfo.GetStockPortfolioRecord();

		count = swipFlipper.getPageCount();		
		if (count != 0)
		{			
			swipFlipper.removeAllViews();
			swipFlipper.smoothScrollToPage(0);
		}			
		//This is new, the first time
//		if (count == 0)
		{
			View     viewObj;
			boolean  rightArrow;
			
			viewObj = CreateStockBalanceInfo(TradeAppInfo.HKDCode, content.GetHKDStockBalance(), false, true);
			swipFlipper.addView(viewObj);
			
			//If USD worth 0, we would not shown
			rightArrow = true;
			if (content.GetUSDStockBalance().equals("0.00"))
				rightArrow = false;

			viewObj = CreateStockBalanceInfo(TradeAppInfo.CNYCode, content.GetCNYStockBalance(), true, rightArrow);
			swipFlipper.addView(viewObj);			
			
			if (rightArrow)
			{
				viewObj = CreateStockBalanceInfo(TradeAppInfo.USDCode, content.GetUSDStockBalance(), true, false);
				swipFlipper.addView(viewObj);	
			}						
		}
//		else
//		{
//			View     viewObj;
//			String   formatText, contentValue;
//			TextView textViewObj;
//			boolean  hasUSD;
//			
//			//Jump back to page 0
//			swipFlipper.smoothScrollToPage(0);
//			viewObj = swipFlipper.getChildContainer().getChildAt(0);
//			if (viewObj != null)
//			{
//				contentValue = content.GetHKDStockBalance();;
//				formatText = Trade_StockFunctionTools.AutoFormatPriceToCents(contentValue);
//				textViewObj = (TextView)viewObj.findViewById(R.id.view_account_stockhold_total_AmountWorth);		
//				textViewObj.setText(TradeAppInfo.HKDSign + Trade_StockFunctionTools .AddFormatToThousand(formatText));
//			}
//			
//			hasUSD = true;
//			if (content.GetUSDStockBalance().equals("0.00"))
//				hasUSD = false;
//			
//			viewObj = swipFlipper.getChildContainer().getChildAt(1);
//			if (viewObj != null)
//			{
//				contentValue = content.GetCNYStockBalance();
//				
//				formatText = Trade_StockFunctionTools.AutoFormatPriceToCents(contentValue);
//				textViewObj = (TextView)viewObj.findViewById(R.id.view_account_stockhold_total_AmountWorth);		
//				textViewObj.setText(TradeAppInfo.CNYSign + Trade_StockFunctionTools .AddFormatToThousand(formatText));
//				
//				if (hasUSD)
//					viewObj.findViewById(R.id.view_account_stockhold_total_RightArrow).setVisibility(View.VISIBLE);
//				else
//					viewObj.findViewById(R.id.view_account_stockhold_total_RightArrow).setVisibility(View.GONE);
//			}
//			
//			/* If we had USD before, and do not have this time */
//			if ((count == 3) && !hasUSD)
//				swipFlipper.getChildContainer().removeViewAt(2);
//			/* If we do not have USD before and now have */
//			else if ((count != 3) && hasUSD)
//			{				
//				viewObj = CreateStockBalanceInfo(TradeAppInfo.USDCode, content.GetUSDStockBalance(), true, false);
//				swipFlipper.addView(viewObj);	
//			}
//			/* We just modify the content */
//			else if (hasUSD)
//			{
//				contentValue = content.GetUSDStockBalance();
//				formatText = Trade_StockFunctionTools.AutoFormatPriceToCents(contentValue);
//				textViewObj = (TextView)viewObj.findViewById(R.id.view_account_stockhold_total_AmountWorth);		
//				textViewObj.setText(TradeAppInfo.USDSign + Trade_StockFunctionTools .AddFormatToThousand(formatText));				
//			}
//		}
	
		count = content.GetStockRecordCount();
		if (count != 0)
			stockHoldList.addAll(content.GetStockRecordListPointer());
		
		stockHoldListAdpater.notifyDataSetChanged();
		stockHoldListView.setSelectionAfterHeaderView();

		// Toast String
		String tmpString;

		if (count == 0)
			tmpString = getString(R.string.youHaveNoRecordText);
		else if (count == 1)
			tmpString = getString(R.string.oneRecordText);
		else
		{
			tmpString = String.valueOf(count) + " ";
			tmpString += getString(R.string.NoOfRecordTexts);
		}
				
		if (toastDisplay != null)
		{
			toastDisplay.cancel();
			toastDisplay.setText(tmpString);
		}
		else
			toastDisplay = Toast.makeText(actContext, tmpString, Toast.LENGTH_SHORT);
		toastDisplay.show();
	}

	@Override
	public void onBackPressed()
	{
		SwitchFreeActivity(Trade_tradingOptionActivity.class);
	}
	
	@Override
	public void onClick(View iViewObj)
	{
		int iObjId;

		iObjId = iViewObj.getId();
		switch (iObjId)
		{
			case R.id.view_acctheader_Home:
				SwitchFreeActivity(Trade_tradingOptionActivity.class);
				break;

			case R.id.view_acctheader_Refresh:
				iViewObj.setClickable(false);					
				StockHoldDataRequest();
				iViewObj.setClickable(true);					
				break;
		}
	}
	

	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		DismissWaitingDialog();
		promptMessage = ShowInfoBox(iContent);
	}
	
	/** Procedure is to prompt confirmation to cancel, password entry, sending
	    if done, show report **/
	private void ShowStockItemActionConfirmation(Trade_StockHoldItem iItem)
	{
		String 		   tradeType;
		TradeConfirmOnViewHoldDialog buySellDialog;
		String tmpString;
		
		//If user has the  item in short, we place a buy order for them
		//and vice versus
		if (iItem.IsShortSale())
			tradeType = Trade_StockReqOrderItem.TRANSACTIONTYPE_BID;
		else
			tradeType = Trade_StockReqOrderItem.TRANSACTIONTYPE_ASK;
		
		buySellDialog = new TradeConfirmOnViewHoldDialog(this);
		// Do the request before setting the view

		if (systemLang.equals("lang_cht"))
			tmpString = iItem.stockCode + "\n" + iItem.chnName;
		else
			tmpString = iItem.stockCode + "\n" + iItem.engName;

		buySellDialog.SetTextContent(tmpString);		
		buySellDialog.SetTextContent2(getString(R.string.stockQuantityText)+ ": ");
				
		tmpString = Trade_StockFunctionTools.AddFormatToThousand(iItem.onHandVolume);
		if (iItem.IsShortSale())
			buySellDialog.SetTextContent3(tmpString, R.color.Red);
		else
			buySellDialog.SetTextContent3(tmpString, R.color.White);
		
		buySellDialog.SetTextContent4(getString(R.string.stockHoldConfirmToActionText) + "?");

		final String uTradeType;
		final String tradeVolume;
		
		uTradeType = tradeType;
		tradeVolume = iItem.onHandVolume;
		buySellDialog.show(new TradeConfirmOnViewHoldDialog.IAppDialogOKCancel()
		{
			@Override
			public void OnDialogCancel(DialogInterface iDialog)
			{
			}

			@Override
			public void OnCancel_Click(DialogInterface iDialog)
			{
			}

			@Override
			public void OnOK_Click(DialogInterface iDialog)
			{
				if (TradeAppInfo.IsDemoAccount() == false)
				{
					// When an OK is pressed, we will start the keypad with
					// available information
					if (IsNetworkAvailable() == false)
					{
						ShowPromptMessage(getString(R.string.commErrorText));
						return;
					}
	
					if (TradeAppInfo.HasSessionTimeExpired())
					{
						ShowTimeExpiredBox();
						return;
					}				
				}
				ObtainStockQuote(stockHoldList.get(focusItemId).stockCode, uTradeType, tradeVolume);
			}
		}, true);
	}

	private final String[] reqSchema = { "StockChiShortName", "ErrorMessage", "LotSize",		
								  "Net", "NetPercentage", "Nominal",				
								  "BidPrice","AskPrice", "CurrencyCode"};
	
	private String lightStreamerID;
	/** Enter from a UI Thread to request a non-null stock code **/
	private void ObtainStockQuote(String iStockCode, String iTradeType, final String iVolume)
	{
		ShowWaitingDialog();		
						
		tradeType   = iTradeType;
		tradeVolume = iVolume;
		requestCode = Trade_StockFunctionTools.FormatFullStockCode(iStockCode);
		/* If we are using demo account, a pretend of network request happen to retrieve
		 * our demo data, the downloadMethod is for us to use if desire */
		if (TradeAppInfo.IsDemoAccount() || TradeAppInfo.IsBMPMode())
		{
			final TradeGetDetailStockQuote quoteRequest;
			
			quoteRequest = new TradeGetDetailStockQuote(actContext);
			//Using 
			quoteRequest.SetRequestQuoteInfo(appHost.IsDevelopment(), requestCode, appHost.GetLSClient_AccountLogonName(), appHost.GetLSClient_SessionKey());
			quoteRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
					new ITradeGetStockQuoteResponse()
					{
						@Override
						public void ResponseFunc(
								boolean iSuccessfulSend,
								TradeGetStockQuoteResult iResponse)
						{
							quoteRequest.Dispose();							
							if (iSuccessfulSend == false)
							{
								ShowPromptMessage(getString(R.string.commErrorText));
								return;
							}
							
							if (!iResponse.resultCode.equals("0"))
							{
								String textValue;
								
								textValue = iResponse.errorMessage;
								if (textValue.equals(""))
									textValue = getString(R.string.commErrorText);
								ShowPromptMessage(textValue);
								if (iResponse.resultCode.equals("-1"))
									appHost.LS_Client_ResetConnection();								
								return;
							}							
							// The process takes too long on UI, we
							// create this to blind the user
							EnterToKeyPad(iResponse.stockQuoteItem, tradeType, tradeVolume);
							// Fool UI Method						
							DismissWaitingDialog_Background();
						}
					});	
			return;
		}
		
		//Now we are using light streamer		
		LS_SubscriptionItem quoteItem;
		
		if (lightStreamerID == null)
			lightStreamerID = LSGetUniqueID();		
		
		quoteItem = new LS_SubscriptionItem("TELETEXT");
		quoteItem.AddSubscribeItem(Trade_StockFunctionTools.RemoveStockCodeFormat(iStockCode));
		quoteItem.SetSubscribeSchema(reqSchema);
		if (LightStreamerSubscribeItem(lightStreamerID, quoteItem, LS_ItemRequestType.NONE, this) == false)
		{		
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			return;
		}	
		
		//Hold a error message after the delay time, 8 seconds
		UIHandler.postDelayed(lightStreamerErrorPrompt, Trade_AppConstant.lightStreamerWaitTime);		
	}
	
	private void LightStreamerTimeoutTaskCancel()
	{
		UIHandler.removeCallbacks(lightStreamerErrorPrompt);		
	}
	
	private Runnable lightStreamerErrorPrompt = new Runnable()
	{
		public void run()
		{
			if (lightStreamerID == null)
				return;
			
			LightStreamerUnsubscribeItem(lightStreamerID);
			
			if (debugMode)
				TDStockLog.i(GetIdentity(), "The LightStreamer(" + lightStreamerID + ")" + "requests timeout.");

			lightStreamerID = null;
			ShowPromptMessage(getString(R.string.commErrorText));	
		}
	};	
	
	/* Subscribing for Account on hold invoking by the server */
	private String lsAccountHoldRequest = null;
	private final String AccountChangeSchema = "CMD";
	private void SubscribeAccountHold()
	{
		if (debugMode)
			TDStockLog.i(GetIdentity(), "*** SubscribeAccountHold");
		
		if (TradeAppInfo.IsDemoAccount() == true)
			return;
		
		if (lsAccountHoldRequest == null)
			lsAccountHoldRequest = LSGetUniqueID();
		
		//Now we are using light streamer		
		LS_SubscriptionItem acctChangeListen;
		String  deviceID;
		
		deviceID = TradeAppInfo.GetDeviceID(actContext);
		
		acctChangeListen = new LS_SubscriptionItem("TRADING");
		acctChangeListen.AddSubscribeItem(deviceID);
		acctChangeListen.AddSubscribeSchema(AccountChangeSchema);

		if (LightStreamerSubscribeItem(lsAccountHoldRequest, acctChangeListen, LS_ItemRequestType.NONE, this) == false)
		{		
			ShowPromptMessage(getString(R.string.SubscribeError_Text));
			return;
		}			
	}
		
	private String  requestCode;
	private String  tradeType;
	private String  tradeVolume;
	private Handler UIHandler = new Handler();
	@Override
	public void onUpdate(String iIdentifier, int iSchemaIndex,
			String iSchemaValue, UpdateInfo iUpdateInfo)
	{		
		if (iIdentifier.equals(lightStreamerID))
		{			
			String tmpValue;
			
			tmpValue = iUpdateInfo.getNewValue("ErrorMessage");
			//Then we can prompt the error
			if ((tmpValue != null) && (tmpValue.length() > 0))
			{
				final String displayText;
				
				if (tmpValue.equals(TradeAppInfo.stockNotFoundText))
					displayText = getString(R.string.StockNotFound_Text);
				else
					displayText = tmpValue;
				Runnable uiAcccess = new Runnable()
				{
					public void run()
					{
						ShowPromptMessage(displayText);
					}
				};					
				UIHandler.post(uiAcccess);
				LightStreamerUnsubscribeItem(iIdentifier);
				requestCode = null;
				lightStreamerID = null;
				//Cancel our timeout task, for all?
				LightStreamerTimeoutTaskCancel();				
				return;
			}

			//Not check for valid date
			tmpValue = iUpdateInfo.getNewValue("StockChiShortName");
			//We consider this is a false value
			if ((tmpValue == null) || (tmpValue.length() == 0))
				return;
			
			//Cancel our timeout task, for all?
			LightStreamerTimeoutTaskCancel();
			
			String 			    tmpValue2, tmpValue3;
			Trade_StockViewInfoItem stockItem;
			
			stockItem = new Trade_StockViewInfoItem(requestCode, tmpValue, null);
			tmpValue = iUpdateInfo.getNewValue("Nominal");
			tmpValue2 = iUpdateInfo.getNewValue("BidPrice");
			tmpValue3 = iUpdateInfo.getNewValue("AskPrice");	
			stockItem.SetPriceInfo(tmpValue, tmpValue2, tmpValue3, false);
			
			tmpValue = iUpdateInfo.getNewValue("Net");
			tmpValue2 = iUpdateInfo.getNewValue("NetPercentage");
			stockItem.SetNetDiffPrice(tmpValue, tmpValue2);
			
			tmpValue = iUpdateInfo.getNewValue("LotSize");
			stockItem.SetStepVolume(tmpValue);

			tmpValue = iUpdateInfo.getNewValue("CurrencyCode");
			stockItem.SetCurrencyCode(tmpValue);			
			
			//Calculate the spread price
			tmpValue = Trade_StockFunctionTools.GetStockPriceSpread(stockItem.GetCurPriceText());
			stockItem.SetSpreadPrice(tmpValue);
						
			LightStreamerUnsubscribeItem(iIdentifier);
			lightStreamerID = null;				
			requestCode = null;		
			
			if (debugMode)
				TDStockLog.i(GetIdentity(), stockItem.toString());
			//Ready to Switch
			EnterToKeyPad(stockItem, tradeType, tradeVolume);				
			// Fool UI Method
			DismissWaitingDialog_Background();
			return;
		}
		
		if (iIdentifier.equals(lsAccountHoldRequest))
		{
			String   tmpValue, tmpValue2;
			String[] stringArray;
			
			tmpValue = iUpdateInfo.getNewValue(AccountChangeSchema);
			//Fault
			if ((tmpValue == null) || (tmpValue.length() == 0))
					return;

			if (debugMode)
				TDStockLog.i(GetIdentity(), "AccountUpdate: " + tmpValue);
			stringArray = tmpValue.split(" ");
			
			int index, count;
			
			count = stringArray.length;
			//Sample o:1234 p:2121
			//We are at the account book, so we will look at the data again		
			for (index = 0; index < count; index++)
			{
				tmpValue  = stringArray[index].trim();
				/* Get the data after the : */
				if (tmpValue.startsWith("o:"))
				{
					tmpValue2 = tmpValue.substring(2);
					if (tmpValue2.equals("0") == false)
					{
						TradeAppInfo.ClearStockHistoryRecord();
						if (debugMode)
							TDStockLog.i(GetIdentity(), "Order book will be needed to updated.");
					}
				}
				else if (tmpValue.startsWith("p:"))
				{
					tmpValue2 = tmpValue.substring(2);	
					if (tmpValue2.equals("0") == false)
					{
						TradeAppInfo.ClearStockPortfolioRecord();				
						if (debugMode)
							TDStockLog.i(GetIdentity(), "Portfolio will be needed to updated.");
					}
				}
			}
			
			if (TradeAppInfo.IsStockPortfolioRecordEmpty())
			{
				Runnable runObject = new Runnable()
				{
					public void run()
					{
						StockHoldDataRequest();
					}
				};
				UIHandler.post(runObject);
			}
		}
	}

	@Override
	public void LS_UserClient_ConnectionReport(
			CONNECTION_STATUS iStatus)
	{
		if (TradeAppInfo.IsDemoAccount())
			return;
		
		//Return to the sign in message display for the application
		if (iStatus == CONNECTION_STATUS.CLOSE_BY_FORCE)
		{
			SetToAppLoginActivity();
			return;	
		}
		
		boolean isConnected;
		
		if (iStatus == CONNECTION_STATUS.CONNECTED)
			isConnected = true;
		else
			isConnected = false;
		
		//Set a dummy ui to the display
		if (isConnected)
			DetachedDisconnectMessage();
		else
		{
			DismissWaitingDialog();			
			AttachDisconnectMessage();
			if (lightStreamerID != null)
			{
				LightStreamerUnsubscribeItem(lightStreamerID);
				lightStreamerID = null;
			}			
		}			
	}

	@Override
	public void ReporterTicker_Response(int iRemainSecond)
	{	}
			
	private PopupWindow lsStatusPopupView = null;
	private View        viewObj = null;
	private Runnable popupWindow_runnable = null;	
	private void AttachDisconnectMessage()
	{
		if (lsStatusPopupView == null)
		{
			LayoutInflater inflatObj = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			
			viewObj  = inflatObj.inflate(R.layout.trade_prompt_msgbox, null);
			viewObj.findViewById(R.id.prompt_msgboxContent).setOnClickListener( new OnClickListener()
			{
				@Override
				public void onClick(View arg0)
				{
					boolean status;
					
					status = appHost.LSClient_Connect(new ILS_UserClient_Authentication_Report()
					{
						@Override
						public void LS_UserClient_Authentication_Response(
								LS_UserClient_Authentication_Result iResponse)
						{
							if ((iResponse.successfulSend == false) || (iResponse.statusCode == null) 
								|| !iResponse.statusCode.equals("0"))
							{
								UIHandler.postDelayed(popupWindow_runnable, Trade_AppConstant.timeDelayForPopup);
								return;
							}												
						}											
					});											
					if (status == true)
						DetachedDisconnectMessage();
				}
	
			});					
			lsStatusPopupView = new PopupWindow(viewObj, 
									 LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			lsStatusPopupView.setAnimationStyle(R.anim.zoom_enter);
			lsStatusPopupView.setOutsideTouchable(true);
		}
				
		if (!lsStatusPopupView.isShowing())
		{
			if (popupWindow_runnable == null)
			{
				popupWindow_runnable = new Runnable()
				{
					public void run()
					{
						lsStatusPopupView.showAtLocation(viewObj, Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL,
												   0, Trade_AppConstant.popupHeightAboveLoc);	
					};
				};
			}
			UIHandler.postDelayed(popupWindow_runnable, Trade_AppConstant.timeDelayForPopup);				
		}	
	}		
	
	private void DetachedDisconnectMessage()
	{
		if (lsStatusPopupView == null)
			return;
		
		if (popupWindow_runnable != null)
			UIHandler.removeCallbacks(popupWindow_runnable);
		
		if (lsStatusPopupView.isShowing())
			lsStatusPopupView.dismiss();
	}	
	
	/** Dismiss after the entering to keypad **/
	private void EnterToKeyPad(Trade_StockViewInfoItem iInfoItem, String iTradeType, String iTradeVolume)
	{
		// When an OK is pressed, we will start the keypad with available
		// information
		Intent intentObj;
		Trade_StockReqOrderItem transferObj;

		intentObj = new Intent(actContext,
				Trade_OrderKeypadActivity.class);
		if (TradeAppInfo.IsDemoAccount())
		{
			transferObj = new Trade_StockReqOrderItem("1234", iInfoItem.stockCode, iInfoItem.chnName,
											  iInfoItem.engName);			
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity("0", "0", "400");
			// Use previous price for setting
			transferObj.SetOrderPrice("882.5");
			transferObj.SetCurrencyCode(TradeAppInfo.HKDCode);
		}
		else
		{
			// Provide with no order no
			transferObj = new Trade_StockReqOrderItem("",
					iInfoItem.stockCode, iInfoItem.chnName,
					iInfoItem.engName);
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity("0", "0", iTradeVolume);			
			// Use previous price for setting
			transferObj.SetOrderPrice(iInfoItem.GetCurBidPriceText());
			transferObj.SetCurrencyCode(iInfoItem.currencyCode);
		}
		// Assume it is a sell order
		transferObj.SetOrderType("E");
		transferObj.SetOrderSide(iTradeType);

		intentObj.putExtra(Trade_AppConstant.stockViewInfo, iInfoItem);
		intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo,
				transferObj);

		// Place the bundle object to the intent
		SwitchForwardActivity(Trade_OrderKeypadActivity.class, intentObj);
	}

	private int	focusItemId	= -1;

	// List Click
	@Override
	public void onItemClick(AdapterView<?> iAdapter, View iView, int iIndex,
			long iArgs)
	{
		int objId;

		objId = iAdapter.getId();
		switch (objId)
		{
			case R.id.stockhold_listItem:
				focusItemId = iIndex;
				ShowStockItemActionConfirmation(stockHoldList
						.get(focusItemId));
				break;
		}
	}

	static private final int	REFRESH_CONTENT	= 1;

	@Override
	public boolean onCreateOptionsMenu(Menu iMenu)
	{
		super.onCreateOptionsMenu(iMenu);
		// Add the menu Item to the menu
		MenuItem menuItemObj = iMenu.add(0, REFRESH_CONTENT, Menu.NONE,
				R.string.updateText);
		menuItemObj.setIcon(R.drawable.ic_menu_lrefresh);
		menuItemObj.setShortcut('0', 'r');

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem iMenu)
	{
		super.onOptionsItemSelected(iMenu);
		switch (iMenu.getItemId())
		{
			case REFRESH_CONTENT:
				StockHoldDataRequest();
				return true;
		}
		return false;
	}

	private boolean StockHoldDataRequest()
	{
		if (debugMode)
			TDStockLog.i(GetIdentity(), "*** StockHoldDataRequest");
		
		if (TradeAppInfo.IsDemoAccount() == false)
		{
			if (IsNetworkAvailable() == false)
			{
				ShowPromptMessage(getString(R.string.commErrorText));
				SubscribeAccountHold();
				return false;
			}
	
			if (TradeAppInfo.HasSessionTimeExpired())
			{
				ShowTimeExpiredBox();
				return false;
			}
		}
		
		if (promptMessage != null)
			promptMessage.dismiss();		
		ShowWaitingDialog();

		TradeGetPortfolio portRequest = new TradeGetPortfolio(actContext);
		portRequest.SetUserInformation(TradeAppInfo.GetUserName());
		portRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeGetPortfolioResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeGetPortfolioResult iResponse)
					{
						if (iSuccessfulSend == false)
							ShowPromptMessage(getString(R.string.commErrorText));
						else
							HandleGetPortfolioResult(iResponse);
						SubscribeAccountHold();
					}
				});
		return true;
	}

	private void HandleGetPortfolioResult(TradeGetPortfolioResult iResult)
	{
		AppDialogOK promptDialog;

		promptDialog = null;
		if ((iResult.BrokerMessage != null)
				&& (iResult.BrokerMessage.length() != 0))
		{
			promptDialog = new AppDialogOK(this);
			promptDialog.SetTextContent(iResult.BrokerMessage);
			promptDialog.SetButtonText(R.string.okText);
			// return features are based on specification
		}

		// Login Session expired and kick user out to the login page
		if (iResult.StatusCode.equals("12"))
		{
			DismissWaitingDialog();
			// Back to the previous window, the  option
			if (promptDialog != null)
			{
				promptDialog.show(new AppDialogOK.IAppDialogOK()
				{
					@Override
					public void OnDialogCancel(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

					@Override
					public void OnOK_Click(DialogInterface iDialog)
					{
						SetToLoginActivity();
					}

				}, true);
				return;
			}
			
			SetToLoginActivity();
			return;
		}

		if (iResult.StatusCode.equals("0"))
		{
			TradeAppInfo.SetStockPortfolioRecord(iResult.portfolio);
			InformationRefresh();
			DismissWaitingDialog();
			return;
		}

		DismissWaitingDialog();
		// Prompt Error if there are one and do not know what to do
		if (promptDialog != null)
			promptDialog.show(null, true);
	}
}
